package com.tinem.platform.service.message.observable;

import com.aliyuncs.IAcsClient;
import com.aliyuncs.dm.model.v20151123.SingleSendMailRequest;
import com.aliyuncs.dm.model.v20151123.SingleSendMailResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.tinem.platform.module.pojo.enums.message.PushChannel;
import com.tinem.platform.module.pojo.vo.message.PushReq;
import com.tinem.platform.module.starter.web.context.GatewayContext;
import com.tinem.platform.service.message.config.AliConfiguration;
import com.tinem.platform.service.message.config.ClientConfiguration;
import com.tinem.platform.service.message.config.MailConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author fzh
 * @version v1
 * @program: platform
 * @className Ali
 * @description
 * @site
 * @company
 * @create 2021-11-15 21:16
 */
@Slf4j
@Service
@Order(100)
public class AliEmail implements ApplicationListener<MessageObservable> {

    @Resource
    AliConfiguration aliConfiguration;
    @Resource
    ClientConfiguration clientConfiguration;

    @Override
    public void onApplicationEvent(MessageObservable event) {
        if(!event.getSource().getPushChannel().equals(PushChannel.ALI_EMAIL)){
            return;
        }
        if(!(event.getBody() instanceof String)){
            return;
        }
        PushReq pushReq = event.getSource();
        SingleSendMailRequest request = new SingleSendMailRequest();
        try {
            request.setAccountName(pushReq.getFrom());
            request.setAddressType(1);
            request.setReplyToAddress(true);
            request.setToAddress(pushReq.getTo());
            request.setSubject(pushReq.getExtMailSubject());
            request.setHtmlBody((String) event.getBody());
            request.setMethod(MethodType.POST);
            ClientConfiguration.Config config = clientConfiguration.getConfig().get(GatewayContext.getClient());
            AliConfiguration.Config aliConfig = aliConfiguration.getConfig().get(config.getAli());
            SingleSendMailResponse httpResponse = aliConfig.iAcsClient().getAcsResponse(request);
            log.info("envid:{}; requestId:{}",httpResponse.getEnvId(),httpResponse.getRequestId());
        } catch (ServerException e ) {
            log.info("",e);
        } catch (ClientException e) {
            log.info("",e);
        }
    }
}
